# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/4/13
# @File   : Rule17_IndCredit_Enforce_3Yr.py
# @E-mail : zhaochen@bbdservice.com

'''eof
name:3年内个人征信强制执行校验
code:IndCredit_Enforce_3Yr_2D
tableName:
columnName:
groups:准入>个人征信校验
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''


import sys
import datetime
import re
from dateutil.relativedelta import relativedelta
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)

    if occurTimes == 1:
        if table == "":
            return ""
        if table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        elif len(table) == 0:
            return [{}]
        else:
            return data.get(tableName)


def Formate(time):
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y-%m-%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y-%m-%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y-%m-%d')
                except:
                    date = None
    return date


# PCE 强制执行记录[1..1]  PF03强制执行记录信息单元 [0,..,*] PF03A 强制执行记录信息段[1,1]
# 立案日期 PF03AR01

def IndCredit_Enforce_3Yr():
    data = IC_DSJ_2D['data']
    PCE = getTable(data, 'PCE', 1)
    if PCE is None:
        return u'缺失值'
    # PF03有0个的情况
    elif PCE == [{}] or PCE == "":
        return 0
    else:
        PF03 = getTable(PCE[0], 'PF03', 0)
        if PF03 is None or PF03 == "":
            return u'缺失值'
        elif PF03 == [{}]:
            return 0
        else:
            result = []
            for p2 in PF03:
                try:
                    PF03A = getTable(p2, 'PF03A', 1)
                    if PF03A in null_type_list:
                        result.append(None)
                    elif PF03A == [{}]:
                        result.append(0)
                    else:
                        registerDate = PF03A[0].get('PF03AR01')
                        registerDateFormat = datetime.datetime.strptime(Formate(registerDate), "%Y-%m-%d")
                        today = datetime.datetime.now()
                        threeYearsAgo = today - relativedelta(years=3)
                        if registerDateFormat > today:
                            result.append(None)
                            continue
                        if registerDateFormat > threeYearsAgo:
                            result.append(1)
                        else:
                            result.append(0)
                except:
                    result.append(None)

        result = filter(lambda x: x is not None, result)
        if len(result) == 0:
            return u'缺失值'
        else:
            return sum(result)

result = IndCredit_Enforce_3Yr()